import ByteUtil from './ByteUtil'

/**
 * 简单加解密工具
 */
export default class EnUtil {
    private static arrToHex = (arr: number[]) => {
        let hex = ''
        arr.forEach((num) => (hex += (num ^ 2).toString(16) + 'u'))
        return hex.substring(0, hex.length - 1)
    }

    private static hexToArr = (str: string) => {
        const hex2int = (hex: string) => {
            var len = hex.length,
                a = new Array(len),
                code
            for (var i = 0; i < len; i++) {
                code = hex.charCodeAt(i)
                if (48 <= code && code < 58) {
                    code -= 48
                } else {
                    code = (code & 0xdf) - 65 + 10
                }
                a[i] = code
            }

            return a.reduce(function (acc, c) {
                acc = 16 * acc + c
                return acc
            }, 0)
        }

        let arr: number[] = []
        str.split('u').forEach((s) => {
            arr.push(parseInt(hex2int(s)) ^ 2)
        })
        return arr
    }

    /**
     * 加密
     * @param str
     * @returns
     */
    static encode = (str: string) => {
        return this.arrToHex(ByteUtil.stringToByte(str))
    }

    /**
     * 解密
     * @param str
     * @returns
     */
    static decode = (str: string) => {
        return ByteUtil.byteToString(this.hexToArr(str))
    }
}
